package com.nanrui.mutualinductor.service;

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.os.RemoteException;
import android.os.SystemClock;
import android.util.Log;

import com.nanrui.mutualinductor.AidlPacket;
import com.nanrui.mutualinductor.BluetoothCallback;
import com.nanrui.mutualinductor.BluetoothInfo;
import com.nanrui.mutualinductor.IBluetooth;
import com.nanrui.mutualinductor.communicate.PacketQueue;
import com.nanrui.mutualinductor.utils.SPUtil;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.UUID;


public class DKService extends Service {

    private IBluetooth.Stub bluetooth;
    private BluetoothAdapter bluetoothAdapter;
    private BluetoothInfo bluetoothInfo;
    private BluetoothReceiver bluetoothReceiver;
    private BluetoothSocket bluetoothSocket;
    private BluetoothCallback callback;
    private InputStream inputStream;
    private OutputStream outputStream;
    private PacketQueue packetQueue;

    private void linkBluetooth(BluetoothDevice paramBluetoothDevice) {
        Object localObject1 = paramBluetoothDevice;
        Object localObject2;
        if (paramBluetoothDevice == null) {
            localObject2 = SPUtil.getLastAddr(this);
            if (localObject2 == null) {
                return;
            }
            Iterator localIterator = this.bluetoothAdapter.getBondedDevices().iterator();
            for (; ; ) {
                localObject1 = paramBluetoothDevice;
                if (!localIterator.hasNext()) {
                    break;
                }
                localObject1 = (BluetoothDevice) localIterator.next();
                if (((BluetoothDevice) localObject1).getAddress().equals(localObject2)) {
                    SystemClock.sleep(1000L);
                    break;
                }
            }
        }
        if (localObject1 == null) {
            return;
        }
        if ((this.bluetoothInfo.getConnectStatus() != 0) && (this.bluetoothInfo.getConnectStatus() != 3)) {
            if ((this.bluetoothInfo.getConnectStatus() == 2) && (!((BluetoothDevice) localObject1).equals(this.bluetoothInfo.getBluetoothDevice()))) {
                this.bluetoothInfo.setNextBluetoothDevice((BluetoothDevice) localObject1);
                unlinkBluetooth();
            }
        } else {
            try {
                try {
                    this.bluetoothInfo.setBluetoothDevice((BluetoothDevice) localObject1);
                    this.bluetoothInfo.setConnectStatus((byte) 1);
                    this.callback.onPreConnect(this.bluetoothInfo);
                    this.bluetoothSocket = ((BluetoothDevice) localObject1).createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
                    this.bluetoothSocket.connect();
                    SystemClock.sleep(1000L);
                    try {
                        SPUtil.setLastAddr(this, ((BluetoothDevice) localObject1).getAddress());
                        this.inputStream = this.bluetoothSocket.getInputStream();
                        this.outputStream = this.bluetoothSocket.getOutputStream();
                        this.bluetoothInfo.setConnectStatus((byte) 2);
                        this.bluetoothInfo.setBluetoothDevice((BluetoothDevice) localObject1);
                        PacketQueue sPacketQueue = new PacketQueue(this.inputStream, this.outputStream);
                        this.packetQueue = sPacketQueue;
                        this.callback.onConnected(this.bluetoothInfo);
                    } catch (RemoteException | IOException e) {
                        e.printStackTrace();
                    }
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                return;
            } catch (IOException e) {
                try {
//                        localObject2 = LOG;
//                        localObject1 = new StringBuilder((StringBuilder) localObject1);
//                        ((StringBuilder) localObject1).append("连接蓝牙失败，错误信息");
//                        ((StringBuilder) localObject1).append(e.getMessage());
//                        ((StringBuilder) localObject1).append(". Socket状态: ");
//                        ((StringBuilder) localObject1).append(this.bluetoothSocket.isConnected());
//                        ((Logger) localObject2).error(((StringBuilder) localObject1).toString());
                    this.bluetoothInfo.setConnectStatus((byte) 3);
                    this.callback.onConnectError(this.bluetoothInfo);
                } catch (RemoteException r) {
                    r.printStackTrace();
                }
            }
        }
    }

    private void unlinkBluetooth() {
        if (this.bluetoothInfo.getConnectStatus() == 2) {
            try {
                this.bluetoothInfo.setConnectStatus((byte) 4);
                this.callback.onPreDisconnect(this.bluetoothInfo);
            } catch (RemoteException localRemoteException) {
                localRemoteException.printStackTrace();
            }
            this.packetQueue.clear();
            try {
                this.inputStream.close();
            } catch (IOException localIOException1) {
                localIOException1.printStackTrace();
            }
            try {
                this.outputStream.close();
            } catch (IOException localIOException2) {
                localIOException2.printStackTrace();
            }
            try {
                this.bluetoothSocket.close();
                this.bluetoothInfo.setBluetoothDevice(null);
                this.bluetoothInfo.setConnectStatus((byte) 0);
            } catch (IOException localIOException3) {
                localIOException3.printStackTrace();
            }
        }
    }

    @Override
    public IBinder onBind(Intent paramIntent) {
        return this.bluetooth;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        this.bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        this.bluetoothInfo = new BluetoothInfo();
        this.bluetoothReceiver = new BluetoothReceiver();
        IntentFilter localIntentFilter = new IntentFilter();

        localIntentFilter.addAction("android.bluetooth.device.action.BOND_STATE_CHANGED");
        localIntentFilter.addAction("android.bluetooth.device.action.NAME_CHANGED");
        localIntentFilter.addAction("android.bluetooth.device.action.ACL_DISCONNECTED");
        localIntentFilter.addAction("android.bluetooth.adapter.action.LOCAL_NAME_CHANGED");
        localIntentFilter.addAction("android.bluetooth.device.action.FOUND");
        localIntentFilter.addAction("android.bluetooth.adapter.action.DISCOVERY_STARTED");
        localIntentFilter.addAction("android.bluetooth.adapter.action.STATE_CHANGED");
        localIntentFilter.addAction("android.bluetooth.adapter.action.DISCOVERY_FINISHED");



//        localIntentFilter.addAction("android.bluetooth.adapter.action.CONNECTION_STATE_CHANGED");
//        localIntentFilter.addAction("android.bluetooth.adapter.action.REQUEST_DISCOVERABLE");
//        localIntentFilter.addAction("android.bluetooth.adapter.action.REQUEST_ENABLE");
//        localIntentFilter.addAction("android.bluetooth.adapter.action.SCAN_MODE_CHANGED");
//        localIntentFilter.addAction("android.bluetooth.device.action.ACL_CONNECTED");
//        localIntentFilter.addAction("android.bluetooth.device.action.ACL_DISCONNECT_REQUESTED");
//        localIntentFilter.addAction("android.bluetooth.device.action.CLASS_CHANGED");
//        localIntentFilter.addAction("android.bluetooth.device.action.PAIRING_REQUEST");
//        localIntentFilter.addAction("android.bluetooth.device.action.UUID");
        registerReceiver(this.bluetoothReceiver, localIntentFilter);
        this.bluetooth = new IBluetooth.Stub() {
            @Override
            public void cancelDiscovery()
                    throws RemoteException {
                bluetoothAdapter.cancelDiscovery();
            }

            @Override
            public void connect(final BluetoothDevice paramAnonymousBluetoothDevice)
                    throws RemoteException {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        linkBluetooth(paramAnonymousBluetoothDevice);
                    }
                }).start();
            }

            @Override
            public void disconnect()
                    throws RemoteException {
                unlinkBluetooth();
            }

            @Override
            public BluetoothInfo getBluetoothInfo()
                    throws RemoteException {
                return bluetoothInfo;
            }

            @Override
            public boolean isEnable()
                    throws RemoteException {
                return bluetoothAdapter.isEnabled();
            }

            @Override
            public void registerCallback(BluetoothCallback paramAnonymousBluetoothCallback)
                    throws RemoteException {

                callback = paramAnonymousBluetoothCallback;
            }


            @Override
            public void sendPacket(AidlPacket paramAnonymousAidlPacket)
                    throws RemoteException {
                if (packetQueue != null) {
                    packetQueue.put(paramAnonymousAidlPacket.getDkPacket(), paramAnonymousAidlPacket.getCallback());
                }
            }

            @Override
            public void startDiscovery()
                    throws RemoteException {
                bluetoothAdapter.startDiscovery();
            }

            @Override
            public void switchBluetooth()
                    throws RemoteException {
                if (bluetoothAdapter.isEnabled()) {
                    bluetoothAdapter.disable();
                } else {
                    bluetoothAdapter.enable();
                }
            }
        };
    }

    @Override
    public void onDestroy() {
        Log.d("DTService", "DKService被终止了!!!");
        unlinkBluetooth();
        unregisterReceiver(this.bluetoothReceiver);
        super.onDestroy();
    }

    class BluetoothReceiver extends BroadcastReceiver {

        BluetoothReceiver() {
        }

        @Override
        public void onReceive(Context paramContext, Intent paramIntent) {
            String str = paramIntent.getAction();
//            Logger localLogger = DKService.LOG;
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("蓝牙广播");
            stringBuilder.append(str);
            Log.d("DTService", stringBuilder.toString());

            switch (str) {

                case "android.bluetooth.device.action.BOND_STATE_CHANGED":
                    try {
                        callback.onBondStateChanged((BluetoothDevice) paramIntent.getParcelableExtra("android.bluetooth.device.extra.DEVICE"), paramIntent.getIntExtra("android.bluetooth.device.extra.BOND_STATE", -1), paramIntent.getIntExtra("android.bluetooth.device.extra.PREVIOUS_BOND_STATE", -1));
                    } catch (RemoteException exception) {
                        exception.printStackTrace();
                    }
                    break;
                case "android.bluetooth.device.action.NAME_CHANGED":

                    break;
                case "android.bluetooth.device.action.ACL_DISCONNECTED":
                    if (((BluetoothDevice) paramIntent.getParcelableExtra("android.bluetooth.device.extra.DEVICE")).getBondState() == 12) {
                        bluetoothInfo.setConnectStatus((byte) 0);
                        bluetoothInfo.setBluetoothDevice(null);
                        try {
                            callback.onDisconnected(bluetoothInfo);
                        } catch (RemoteException exception) {
                            exception.printStackTrace();
                        }
                        if (bluetoothInfo.getNextBluetoothDevice() != null) {
                            linkBluetooth(bluetoothInfo.getNextBluetoothDevice());
                            bluetoothInfo.setNextBluetoothDevice(null);
                        }
                    }
                    break;
                case "android.bluetooth.adapter.action.LOCAL_NAME_CHANGED":

                    break;
                case "android.bluetooth.device.action.FOUND":

                    try {
                        callback.onFound((BluetoothDevice) paramIntent.getParcelableExtra("android.bluetooth.device.extra.DEVICE"));
                    } catch (RemoteException exception) {
                        exception.printStackTrace();
                    }
                    break;

                case "android.bluetooth.adapter.action.DISCOVERY_STARTED":

                    try {
                        callback.onDiscoveryStarted();
                    } catch (RemoteException exception) {
                        exception.printStackTrace();
                    }
                    break;

                case "android.bluetooth.adapter.action.STATE_CHANGED":

                    int i = paramIntent.getIntExtra("android.bluetooth.adapter.extra.STATE", -1);
                    int j = paramIntent.getIntExtra("android.bluetooth.adapter.extra.PREVIOUS_STATE", -1);
                    try {
                        callback.onStateChanged(i, j);
                    } catch (RemoteException exception) {
                        exception.printStackTrace();
                    }
                    break;
                case "android.bluetooth.adapter.action.DISCOVERY_FINISHED":
                    try {
                        callback.onDiscoveryFinished();
                    } catch (RemoteException exception) {
                        exception.printStackTrace();
                    }
                    break;

                default:
                    break;
            }
        }
    }


}

